package com.hn658.base.message.comet.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.restlet.data.Status;
import org.restlet.engine.adapter.HttpResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.hn658.base.message.comet.context.CurrentUserContext;
import com.hn658.base.message.comet.enums.ExceptionType;
import com.hn658.base.message.common.exceptions.FilterException;
import com.hn658.framework.cache.message.MessageCache;
import com.hn658.framework.exception.ExceptionManager;
import com.hn658.framework.logging.Logger;
import com.hn658.framework.logging.LoggerFactory;
import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.framework.shared.utils.JsonMapper;

/**
 * 拦截器基类
 * @author ztjie
 */
public class ExceptionFilter extends AbstractBaseFilter{
    /**
     * 日志记录器
     */
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    protected JsonMapper mapper = JsonMapper.nonEmptyMapper();
    
    protected ApplicationContext ac;
    
    protected MessageCache messageCache;
    
    @Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ac = WebApplicationContextUtils.getWebApplicationContext(filterConfig
				.getServletContext());
		messageCache = ac.getBean(MessageCache.class);
	}
    
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			HttpServletResponse res = (HttpServletResponse) response;
			ExceptionManager.getInstance().getExceptionPolicy().handleException(null, null, null, e);
			if (FilterException.class.isAssignableFrom(e.getClass())) {
				res.setStatus(ExceptionType.NoResetException.getCode());
			} else {
				logger.error(LogCategory.APPLICATION, e.getMessage(), e);
				res.setStatus(ExceptionType.ResetException.getCode());
			}
			response.getOutputStream().flush();
		} finally{
			// 清理上下文
			CurrentUserContext.clean();
	        
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
